%% Temple university CIS 2033
% A modern Introduction to Probability and Statistics
% Chapter 3 - Conditional probability and independence
%
% Author: Djordje Gligorijevic
% email: gligorijevic@temple.edu

%% The probability of no coincident birthdays
%
% If there are n people in a classroom, what is the probability that
% there is no coincident birthday.
% 
% General solution:
% 
% P = (1-(n-1)/365)*(1-(n-2)/365)*...*(1-(1)/365)

clc; 
clear all

eventBn1 = 'the birthday of the nth person does not coincide with a birthday of any of the ?rst n ? 1 persons'

studentsCount = 100; % maximum number of people in classroom
xAxis = 1:studentsCount;
prevPnot = 1; % initialize probability

for i = studentsCount:-1:1
    Pnot = prevPnot*(1 - (studentsCount - i)/365); % probability that no birthdays are the same
    P(i) = Pnot;
    prevPnot = Pnot;
end


% because we are counting probabilities in reverse order than count of
% people in a classroom we flip the vector of probabilties using fliplr()
% function
figure
plot(xAxis, fliplr(P), '.-')
title(sprintf('The probability P(Bn) of no coincident birthdays for n = 1,...,%i',studentsCount))
xlabel('Number of people')
ylabel('P(B)')
grid on
hold on

%% The probability to have two coindident birthdays
%
% If there are n people in a classroom, what is the probability that
% at least two of them have the same birthday?
% 
% General solution:
% P = 1-365!/(365-n)!/365^n
% 
% If you try to solve this with large n (e.g. 30, for which the solution is
% 29%) with the factorial function like so:
% 
% P = 1-factorial(365)/factorial(365-30)/365^30, 
% 
% Matlab will output NaN because Matlab tries to compute very large values here.
% 
% The approach below is to start from n=1 and at each step use the
% previous step's result to avoid dealing with large numbers.
% 
% Samil Korkmaz, 31.01.2012

clc; 
clearvars -except eventBn1

eventBn2 = 'There are at least two coincident birthdays amonth first n people';

studentsCount = 100; % maximum number of people in classroom
xAxis = 1:studentsCount;
prevPnot = 1; % initialize probability
for i = 1:studentsCount
    Pnot = prevPnot*(365-i+1)/365; % probability that no birthdays are the same
    P(i) = 1-Pnot; % probability that at least two birthdays are the same
    prevPnot = Pnot;
end

plot(xAxis, P, '.-')
title(sprintf('The probability P(Bn) of at least two coincident birthdays for n = 1,...,%i', studentsCount))
xlabel('Number of people')
ylabel('P(Bn)')
grid on
legend(eventBn1, eventBn2)


